﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Data.Models;

namespace Parafarmacia
{
    public partial class masterPage : System.Web.UI.MasterPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            FillDatos();
            GetAllControlsEditables();

        }

        public void GetAllControlsEditables()
        {
            ContentPlaceHolder cph = (ContentPlaceHolder)FindControl("MainContent");
            string Pagina = Path.GetFileName(Request.PhysicalPath);

            try
            {
                string str = Request.Url.AbsolutePath.Substring(1);
                str = str.Substring(0, str.IndexOf("/"));
                Pagina = str; //RouteMaps
            }
            catch { }

            VerifyControl(Pagina, cph.Controls);

        }

        private void VerifyControl(string NombrePagina, ControlCollection controls)
        {
            using (var db = new dbParafarmaciaContext())
            {
                var query = from c in db.tblContenidos where c.NombrePagina == NombrePagina select c;

                foreach (Control ctl in controls)
                {
                    if (ctl is Label)
                    {
                        Label lbl = (Label)ctl;

                        var contCtl = from cont in query.ToList() where cont.NombreControl == lbl.ID select cont;

                        if (contCtl.Count() == 0)
                        {
                            tblContenido cont = new tblContenido();
                            cont.NombreControl = lbl.ID;
                            cont.NombrePagina = NombrePagina;

                            db.tblContenidos.Add(cont);
                            db.SaveChanges();
                        }
                    }
                }
            }
        }

        private void FillDatos()
        {
            using (var db = new dbParafarmaciaContext())
            {
                var info = from i in db.tblEmpresaInfos select i;

                foreach (tblEmpresaInfo cont in info)
                {
                    lblEmpresa.Text = cont.Empresa;
                    lblDireccion.Text = cont.Direccion1;
                    lblProvincia.Text = cont.CodigoPostal + " " + cont.Provincia;
                    lblTelefono.Text = cont.teléfono1;
                    lblEmail.Text = cont.Email;
                }
            }

            ContentPlaceHolder cph = (ContentPlaceHolder)FindControl("MainContent");
            string Pagina = Path.GetFileName(Request.PhysicalPath);

            Utils.FillContenidoContentPlaceHolder(cph, Pagina);
        }
    }
}